<?php
namespace app\index\controller;

use app\common\model\Details;
use app\common\model\Goods;
use app\common\model\GoodsCate;
use app\common\model\Msg;
use app\index\validate\Address;
use app\index\validate\Business;
use app\index\validate\Withdraw;
use think\db;
use app\common\model\Param;
use app\common\model\Logs;
use app\common\model\Account;
use app\common\model\Rec;

use app\common\model\User as U;

class User extends Common
{

    /**
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub

        if (!$this->checkLogin()) {
            if (!isAjaxPost()) {
                $params = input();
                $get = [];
                foreach ($params as $k=>$v) {
                    if (!empty($v)) {
                        $get[$k] = $v;
                    }
                }
                session('redirect_uri', url('', $get));
            }
            return $this->myReturn('你还没有登录，请前往登录', url('login/index'));
        }
    }

    /**
     * 退出登录
     */
    public function logout() {
        session('user', null);
        session('openId', null);

        return $this->jsonSuccess('退出成功');
    }

    /**
     * 消息列表
     * @return mixed
     */
    public function msg() {
        return $this->fetch();
    }

    /**
     * 获取消息列表
     * @param int $state
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function getMsgList($state=0) {
        !isAjaxPost() && die;
        $user_id = session('user.id');
        // if ($state > 0) {
        //     $where = [
        //         'user_id' => $user_id
        //     ];
        // } else {
        //     //只能看到用户注册之后的通知
        //     $where = [
        //         'user_id' => 0,
        //         'add_time' => ['egt', session('user.add_time')]
        //     ];
        // }


        $model = new Msg();
        $pageSize = 10;
        $list = $model->order('id desc')->paginate($pageSize, true);
        $ids = [];
        foreach ($list as &$v) {
            if (strpos($v['read_user_id'], ",$user_id,") === false) {
                //未读
                $ids[] = $v['id'];
                $v['is_read'] = 0;
            } else {
                //已读
                $v['is_read'] = 1;
            }
            $v['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
        }
        //未读改为已读
        $model->save(['read_user_id'=>['exp', "concat(`read_user_id`, '$user_id,')"]], ['id'=>['in', $ids]]);

        return $this->jsonSuccess('', $list);
    }

    /**
     * 用户中心首页
     * @return mixed
     */
    public function index() {
        $info = session('user');
        // $model = new Msg();
        // $where = "(user_id=0 OR user_id={$info['id']}) AND read_user_id NOT LIKE '%,{$info['id']},%'";

        // $info['msg_count'] = $model->where($where)->count();
        // $info['business_type'] = db::name('business')->where(['user_id'=>$info['id']])->value('status');
        // $order_model = new \app\common\model\Order();
        // $info['order_count'] = $order_model->where(['user_id'=>$info['id'],'status'=>['in',[1,2,3,4]]])->group('status')->column('count(id)', 'status');
        // $this->assign('full_amount', getSystemParams('full_amount'));
        $this->assign('info', $info);
        return $this->fetch('index2');
    }

    /**
     * 我的钱包
     */
    public function wallet() {
        return $this->fetch();
    }
    /**
     * 我的金额
     */
    public function amount() {
        return $this->fetch();
    }
    


    /**
     * 提现申请
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function withdraw() {
        $user_info = session('user');
        if (isAjaxPost()) {
            $data = [
                'user_id' => $user_info['id'],
                'orderno' => createOrder(),
                'user_type' => input('post.user_type', 0, 'intval'),
                'amount' => amountFormat(input('post.amount', 0, 'floatval')),
                'bank' => input('post.bank', '', 'trim'),
                'card' => input('post.card', '', 'trim'),
                'name' => input('post.name', '', 'trim'),
                'add_time' => time()
            ];

            $validate = new Withdraw();
            if (!$validate->check($data)) {
                return $this->jsonError($validate->getError());
            }

            $model = new \app\common\model\Withdraw();
            $model->startTrans();
            if (!$model->insert($data)) {
                $model->rollback();
                return $this->jsonError('申请提交失败');
            }
            //减余额
            if ($data['user_type'] == 0) {
                if (db::name('user')->where(['id' => $user_info['id']])->setDec('balance', $data['amount']) === false) {
                    $model->rollback();
                    return $this->jsonError('申请提交失败');
                }
            } else {
                if (db::name('business')->where(['user_id' => $user_info['id']])->setDec('balance', $data['amount']) === false) {
                    $model->rollback();
                    return $this->jsonError('申请提交失败');
                }
            }
            //资金记录
            $log = [
                'content' => "申请提现,单号：{$data['orderno']}",
                'amount' => $data['amount'],
                'user_id' => $data['user_id'],
                'user_type' => $data['user_type'],
                'type' => 4,
                'symbol' => '-',
                'balance' => db::name('user')->where('id', $data['user_id'])->value('balance'),
                'add_time' => time()
            ];
            if (!db::name('details')->insert($log)) {
                $model->rollback();
                return $this->jsonError('申请提交失败');
            }
            $model->commit();
            return $this->jsonSuccess('申请提交成功');
        }

        $min_withdraw_amount = getSystemParams('min_withdraw_amount');
        $user_type = input('user_type', 0, 'intval');
        if ($user_type) {
            $uid = $user_info['id'];
            $balance = db::name('business')->where(['user_id'=>$uid])->value('balance');
        } else {
            $balance = $user_info['balance'];
        }
        if ($balance <= $min_withdraw_amount) {
            layerExit('余额过低，无法申请提现');
        }
        $this->assign('balance', $balance);
        $this->assign('min_withdraw_amount', $min_withdraw_amount);
        $this->assign('bank_list', getBankList());
        return $this->fetch();
    }

    /**
     * 提现列表
     * @return mixed
     */
    public function withdraw_list() {
        return $this->fetch();
    }

    /**
     * @return mixed
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function withdraw_info() {
        $id = input('id', 0, 'intval');
        $id <= 0 && layerExit('提现记录不存在');

        $model = new \app\common\model\Withdraw();
        $info = $model->where(['id'=>$id,'user_id'=>session('user.id')])->find();
        empty($info) && layerExit('提现记录不存在');
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 获取提现列表
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function getWithdrawList() {
        !isAjaxPost() && die;
        $user = session('user');
        $user_type = input('post.user_type', 0, 'intval');
        $user_id = $user['id'];
        $where = [
            'user_id' => $user_id,
            'user_type' => $user_type
        ];

        $model = new \app\common\model\Withdraw();
        $pageSize = 10;
        $list = $model->where($where)->order('id desc')->field('id,orderno,amount,status,bank,card,add_time')->paginate($pageSize, true);

        foreach ($list as &$v) {
            $v['state'] = getWithdrawState($v['status']);
            $v['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
            $v = $v->toArray();
        }

        return $this->jsonSuccess('', $list);
    }

    /**
     * 资金明细 个人钱包明细
     * @return mixed
     */
    public function details() {
        $state_list = getDetailsState();
        unset($state_list[6],$state_list[7],$state_list[1]);
        $this->assign('state_list', $state_list);
        return $this->fetch();
    }

    /**
     * 获取资金明细列表
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function getDetailsList() {
        !isAjaxPost() && die;
        $user = session('user');
        $user_id = $user['id'];
        $where = [
            'user_id' => $user_id,
        ];
        // $model = new Details();
        $pageSize = 10;
        $list = db('recharge')->where($where)->order('id desc')->page(input('page'),10)->select();
        foreach ($list as $key=>&$v) {
            
            $v['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
          
        }
        return $this->jsonSuccess('', $list);
    }

    /**
     * 我的收货地址
     * @return mixed
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function address() {
        $list = db::name('address')->where(['user_id'=>session('user.id')])->order('is_default desc,id desc')->select();
        $this->assign('list', $list);
        session('address_uri', '');
        return $this->fetch();
    }

    /**
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setDefault() {
        !isAjaxPost() && die;
        $id = input('post.id', 0, 'intval');
        if ($id <= 0) {
            return $this->jsonError('缺少必要参数');
        }

        $user_id = session('user.id');
        db::name('address')->where(['user_id'=>$user_id, 'is_default'=>1])->setField('is_default', 0);
        db::name('address')->where(['user_id'=>$user_id,'id'=>$id])->setField('is_default', 1);
        return $this->jsonSuccess('');
    }

    /**
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delAddress() {
        !isAjaxPost() && die;
        $id = input('post.id', 0, 'intval');
        if ($id <= 0) {
            return $this->jsonError('缺少必要参数');
        }

        $user_id = session('user.id');
        if (db::name('address')->where(['user_id'=>$user_id,'id'=>$id])->delete() !== false) {
            return $this->jsonSuccess('删除成功');
        } else {
            return $this->jsonError('删除失败');
        }

    }

    /**
     * 添加/编辑收货地址
     * @param int $id
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function save_address($id=0) {
        if (isAjaxPost()) {
            $data = [
                'name' => input('post.name', '', 'trim'),
                'tel' => input('post.tel', '', 'trim'),
                'sheng_id' => input('post.sheng_id', 0, 'intval'),
                'city_id' => input('post.city_id', 0, 'intval'),
                'area_id' => input('post.area_id', 0, 'intval'),
                'sca_name' => input('post.sca_name', '', 'trim'),
                'address' => input('post.address', '', 'trim'),
                'is_default' => input('post.is_default', 0, 'intval'),
                'user_id' => session('user.id')
            ];

            $validate = new Address();
            if (!$validate->check($data)) {
                return $this->jsonError($validate->getError());
            }

            if ($data['is_default'] == 1) {
                db::name('address')->where(['user_id'=>$data['user_id']])->setField('is_default', 0);
            }
            if ($id > 0) {
                if (db::name('address')->where(['id'=>$id,'user_id'=>$data['user_id']])->update($data) !== false) {
                    return $this->jsonSuccess('编辑成功');
                } else {
                    return $this->jsonError('编辑失败');
                }
            } else {
                if (db::name('address')->where(['user_id' => $data['user_id']])->count() >= 10) {
                    return $this->jsonError('最多只能添加10个收货地址');
                }

                if ($data['id'] = db::name('address')->insertGetId($data)) {
                    return $this->jsonSuccess('操作成功', $data);
                } else {
                    return $this->jsonError('添加失败');
                }
            }
        }
        if ($id > 0) {
            $info = db::name('address')->where(['id'=>$id,'user_id'=>session('user.id')])->find();
            $this->assign('info', $info);
        }
        return $this->fetch();
    }

    /**
     * 个人信息
     * @return mixed
     */
    public function info() {
        return $this->fetch();
    }

    /**
     * 修改头像
     * @return \think\response\Json
     */
    public function edit_head_img() {
        if (request()->isPost()) {
            $img = myUpload();
            if (empty($img[0])) {
                return $this->jsonError('上传失败');
            }

            return $this->editUserInfo('img', $img[0]);
        }
        return $this->fetch();
    }

    /**
     * 修改姓名
     * @return mixed|\think\response\Json
     */
    public function edit_name() {
        if (isAjaxPost()) {
            $name = input('post.name', '', 'trim');
            if (empty($name)) {
                return $this->jsonError('请填写用户姓名');
            }

            return $this->editUserInfo('name', $name);
        }
        return $this->fetch();
    }

    /**
     * 修改手机
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function edit_tel() {
        if (isAjaxPost()) {
            $tel = input('post.tel', '', 'trim');
            $code = input('post.code', '', 'trim');
            if (empty($tel)) {
                return $this->jsonError('请填写手机号');
            }
            if (!checkTel($tel)) {
                return $this->jsonError('手机号格式错误');
            }
            if (empty($code)) {
                return $this->jsonError('请填写验证码');
            }
            $res = checkCode($tel, $code);
            if ($res !== true) {
                return $this->jsonError($res);
            }

            return $this->editUserInfo('tel', $tel);
        }
        return $this->fetch();
    }

    /**
     * 修改密码
     * @return mixed|\think\response\Json
     */
    public function edit_pwd() {
        if (isAjaxPost()) {
            $pwd = input('post.pwd', '', 'trim');
            $password = input('post.password', '', 'trim');
            $type=input('type');
            $confirm_password = input('post.confirm_password', '', 'trim');
            if (empty($pwd)) {
                return $this->jsonError('请填写旧密码');
            }
            if (empty($password)) {
                return $this->jsonError('请填写新密码');
            }
            if ($password != $confirm_password) {
                return $this->jsonError('两次密码输入不一致');
            }
            if($type==1){
                $where=[
                    'id'=>session('user.id'),
                    'password'=>md5($pwd)
                ];
                $fie='password';
            }else{
                $where=[
                    'id'=>session('user.id'),
                    'pay_password'=>md5($pwd)
                ];
                $fie='pay_password';
            }
            if (db::name('user')->where($where)->count() <= 0) {
                return $this->jsonError('旧密码错误');
            }
            return $this->editUserInfo($fie, md5($password));
        }
        return $this->fetch();
    }

    private function editUserInfo($field, $value) {
        $model = new \app\common\model\User();
        if ($model->where(['id' => session('user.id')])->setField($field, $value) !== false) {
            return $this->jsonSuccess('修改成功', $value);
        } else {
            return $this->jsonError('修改失败');
        }
    }






    /********* 分销中心开始 **********/

    /**
     * 分销中心首页
     * @return mixed
     */
    public function fx() {
        $user_info = session('user');
        //一代
        $one = $this->getFxData($user_info['id']);
        $two = $three = [
            'num' => 0, 'amount' => 0
        ];
        if ($one['num'] > 0) {
            $two = $this->getFxData($one['ids']);
            if ($two['num'] > 0) {
                $three = $this->getFxData($two['ids']);
            }
        }
        $assign = [
            'integral' => $user_info['integral'],
            'code' => $user_info['code'],
            'one' => $one,
            'two' => $two,
            'three' => $three
        ];
        session('sons', $assign);
        return $this->fetch('', $assign);
    }

    /**
     * 推广二维码
     * @return mixed
     */
    public function fx_qrcode() {
        return $this->fetch();
    }

    /**
     * 重新生成二维码
     * @return \think\response\Json
     */
    public function reSaveQrcode() {
        !isAjaxPost() && die;
        saveQrcode(session('user'));
        return $this->jsonSuccess('操作成功');
    }

    /**
     * 资金明细 分销中心积分明细
     * @return mixed
     */
    public function details_fx() {
        $state_list = getDetailsState();
        foreach ($state_list as $k=>$v) {
            if (!in_array($k, [6,7])) {
                unset($state_list[$k]);
            }
        }
        $this->assign('state_list', $state_list);
        $this->assign('user_type', 1);
        return $this->fetch('details');
    }

    /**
     * 获取分销数据
     * @param $ids
     * @return array
     */
    private function getFxData($ids) {
        return getFxData($ids);
    }

    /**
     * 下级列表
     * @return mixed|void
     */
    public function fx_list() {
        if (!session('?sons')) {
            return $this->redirect('fx');
        }
        return $this->fetch();
    }

    /**
     * 获取下级列表
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function getFxList() {
        !isAjaxPost() && die;
        $user_id = session('user.id');
        $level = input('post.level', 0, 'intval');
        $sons = session('sons');
        switch ($level) {
            case 1:
                $where['pid'] = $user_id;
                break;
            case 2:
                if (empty($sons['one']['ids'])) {
                    return $this->jsonSuccess('', ['data'=>[]]);
                }
                $where['pid'] = ['in', $sons['one']['ids']];
                break;
            case 3:
                if (empty($sons['two']['ids'])) {
                    return $this->jsonSuccess('', ['data'=>[]]);
                }
                $where['pid'] = ['in', $sons['two']['ids']];
                break;
            default:
                return $this->jsonSuccess('', ['data'=>[]]);
        }


        $model = new \app\common\model\User();
        $pageSize = 10;
        $list = $model->where($where)->order('id asc')->field('id,img,name,tel')->paginate($pageSize, true);
        $order_model = new \app\common\model\Order();
        foreach ($list as &$v) {
            $v['amount'] = $order_model->where(['user_id'=>$v['id'],'status'=>['in', [2,3,4,5]]])->sum('amount');
        }

        return $this->jsonSuccess('', $list);
    }

    /********* 分销中心结束 **********/






    /********* 商家中心开始 **********/

    /**
     * 商家中心
     * @return mixed
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function business() {
        $user = session('user');
        $uid = $user['id'];
        $business = db::name('business')->where(['user_id'=>$uid])->find();
        $sys=(new param())->findParam(['id'=>1]);
        $band=explode('/',unserialize($sys['content'])['band']);
        switch ($business['status']) {
            case 2:
            case 4:
            case 5:
                //审核通过
                $this->assign('info', $business);
                return $this->fetch('business');
                break;
            case 1:
                //审核中
            case 3:
                //审核未通过
                $band_arr=[];
                $u_band=explode('/',$business['band']);
                foreach ($band as $key => &$value) {
                    $band_arr[$key]['name']=$value;
                    $band_arr[$key]['check']=in_array($value,$u_band)?1:0;
                }
                $this->assign('info', $business);
                $this->assign('band_arr', $band_arr);

                return $this->fetch('business_applying');
                break;
            default:
                //未申请
                $content = db::name('news')->where(['id'=>1])->value('content');
                $this->assign('content', $content);
                return $this->fetch('business_no_apply');
        }
    }

    /**
     * @return mixed
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function business_applying() {
        $user = session('user');
        $uid = $user['id'];
        $business = db::name('business')->where(['user_id'=>$uid])->find();
        $this->assign('info', $business);
        return $this->fetch();
    }

    /**
     * 商家申请
     * @param int $id
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function business_apply($id=0) {
        $user = session('user');
        $user_id = $user['id'];
        if (isAjaxPost()) {
            if ($id > 0) {
                $info = db::name('business')->where(['id'=>$id,'user_id' => $user_id])->find();
                if (empty($info)) {
                    $id = 0;
                }
            }
            $data = [
                'title' => input('post.title', '', 'trim'),
                'name' => input('post.name', '', 'trim'),
                'tel' => input('post.tel', '', 'trim'),
                'address' => input('post.address', '', 'trim'),
                'license' => input('post.license', '', 'trim'),
                'user_id' => $user_id,
                'band'=>ltrim(input('post.band'),'/'),
                'status' => ($id > 0 && ($info['status'] == 2 || $info['status'] == 5)) ? 4 : 1
            ];
            $validate = new Business();
            if (!$validate->check($data)) {
                return $this->jsonError($validate->getError());
            }

            if ($id > 0) {
                if (db::name('business')->where(['id'=>$id,'user_id' => $user_id])->update($data) !== false) {
                    return $this->jsonSuccess('申请提交成功');
                } else {
                    return $this->jsonError('申请提交失败');
                }
            } else {
                if (db::name('business')->insert($data) !== false) {
                    return $this->jsonSuccess('申请提交成功');
                } else {
                    return $this->jsonError('申请提交失败');
                }
            }
        }
        $sys=(new param())->findParam(['id'=>1]);
        $band=explode('/',unserialize($sys['content'])['band']);
        $band_arr=[];
        if ($id > 0) {
            $business = db::name('business')->where(['id'=>$id,'user_id' => $user_id])->find();
            $u_band=explode('/',unserialize($business['band']));
            
            $this->assign('info', $business);
        }
        foreach ($band as $key => &$value) {
            $band_arr[$key]['name']=$value;
            $band_arr[$key]['check']=in_array($value,$u_band)?1:0;
        }
        $this->assign('band_arr', $band_arr);
        return $this->fetch();
    }

    /**
     * 明细记录
     * @return mixed
     */
    public function details_business() {
        $state_list = getDetailsState();
        foreach ($state_list as $k=>$v) {
            if (!in_array($k, [3,4])) {
                unset($state_list[$k]);
            }
        }
        $this->assign('state_list', $state_list);
        return $this->fetch('details');
    }

    /**
     * 积分记录
     * @return mixed
     */
    public function details_integral() {
        $state_list = getDetailsState();
        foreach ($state_list as $k=>$v) {
            if (!in_array($k, [6,7])) {
                unset($state_list[$k]);
            }
        }
        $this->assign('state_list', $state_list);
        return $this->fetch('details');
    }

    /**
     * 收款
     */
    public function receivables() {
        if (isAjaxPost()) {
            $amount = amountFormat(input('post.amount', 0, 'floatval'));
            if ($amount <= 0) {
                return $this->jsonError('金额必须大于0');
            }

            $user = session('user');
            $imgUrl = "./qrcode/pay/{$user['id']}.png" ;
            //头像扒上去
            $image = \think\Image::open( './static/index/img/a8.jpg');

            //生成用户的二维码
            $orderno = createOrder();
            $qrcodeUrl = "./qrcode/pay/temp{$orderno}.png" ;
            $uri = "http://{$_SERVER['HTTP_HOST']}".url('pay', ['business_user_id'=>$user['id'],'amount'=>$amount]);
            $qrcode = myqrcode($uri, "temp{$orderno}.png", './qrcode/pay', './qrcode/logo.png','#ffffff','#000000',15);

            //头像扒上去
//            $image = \think\Image::open( $imgUrl);
            $image->water( $qrcode ,[338,666])->save($imgUrl);

            //删除生成的二维码
            unlink( $qrcodeUrl ) ;

            return $this->jsonSuccess('', $imgUrl);
        }
        return $this->fetch();
    }

    /**
     * 用户付款
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function pay() {
        $business_user_id = input('business_user_id', 0, 'intval');
        $amount = amountFormat(input('amount', 0, 'floatval'));
        if ($business_user_id <= 0) {
            return $this->myReturn('缺少必要参数', url('index'));
        }
        $user = session('user');
        if ($business_user_id == $user['id']) {
            return $this->myReturn('不能向自己支付', url('index'));
        }
        if ($amount <= 0) {
            return $this->myReturn('支付金额必须大于0', url('index'));
        }
        if ($user['balance'] <= 0) {
            return $this->myReturn('您目前余额为0,不能支付', url('index'));
        }
        $business_info = db::name('business')->where(['user_id'=>$business_user_id, 'status'=>['in', [2,4,5]]])->find();
        if (empty($business_info)) {
            return $this->myReturn('商户不存在');
        }

        if ($user['balance'] > $amount) {
            $balance_pay = $amount;
        } else {
            $balance_pay = $user['balance'];
        }

        if (isAjaxPost()) {
            $user_model = new \app\common\model\User();
            $user_model->startTrans();
            //减余额
            if ($user_model->where(['id'=>$user['id']])->setDec('balance', $balance_pay) === false) {
                $user_model->rollback();
                return $this->jsonError('支付失败');
            }
            //商家加积分
            $integral = amountFormat($balance_pay * getSystemParams('integral_rate'));
            if ($integral <= 0 || db::name('business')->where(['user_id'=>$business_user_id])->setInc('integral', $integral) === false) {
                $user_model->rollback();
                return $this->jsonError('收款失败');
            }
            //资金记录
            //用户减余额
            $log[] = [
                'content' => '扫码支付',
                'amount' => $balance_pay,
                'add_time' => time(),
                'user_id' => $user['id'],
                'user_type' => 0,
                'type' => 5,
                'symbol' => '-',
                'balance' => $user_model->where('id', $user['id'])->value('balance')
            ];
            //商家加积分
            $log[] = [
                'content' => '二维码收款',
                'amount' => $integral,
                'add_time' => time(),
                'user_id' => $business_user_id,
                'user_type' => 1,
                'type' => 6,
                'symbol' => '+',
                'balance' => db::name('business')->where('id', $business_user_id)->value('integral')
            ];
            if (!db::name('details')->insertAll($log)) {
                $user_model->rollback();
                return $this->jsonError('资金明细记录失败');
            }

            $user_model->commit();
            return $this->jsonSuccess('支付成功', ['balance_pay'=>$balance_pay,'amount'=>amountFormat($amount-$balance_pay)]);
        }

        $business_info['img'] = db::name('user')->where(['id'=>$business_user_id])->value('img');
        $business_info['hot'] = db::name('details')->where(['user_id'=>$business_user_id,'type'=>6,'user_type'=>1])->count();
        $this->assign('info', $business_info);
        $this->assign('balance', $user['balance']);
        $this->assign('balance_pay', $balance_pay);

        return $this->fetch();
    }

    public function manage() {
        return $this->fetch();
    }
    public function register() {
        return $this->fetch();
    }
    public function user() {
        return $this->fetch();
    }

    /**
     * @return mixed
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function user_goods() {
        $data = [
            'user_id' => input('user_id', 0, 'intval'),
            'name' => input('name', '', 'trim'),
        ];
        if (empty($data['name']) || $data['user_id'] <= 0) {
            layerExit('缺少必要参数', url('manage'));
        }
        session('user_goods', $data);
        $model = new GoodsCate();
        $this->assign('list', $model->getList());
        $user_cart = session('user_cart');
        if (empty($user_cart[session('user_goods.user_id')])) {
            $num = 0;
        } else {
            $num = count($user_cart[session('user_goods.user_id')]);
        }
        $this->assign('num', $num);
        return $this->fetch();
    }

    /**
     * 加入购物车
     * @return \think\response\Json
     */
    public function addCart() {
        !isAjaxPost() && die;
        $user_cart = session('user_cart');
        $num = session('user_cart_num');
        $goods_id = input('post.goods_id', 0, 'intval');
        if (empty($user_cart[session('user_goods.user_id')])) {
            $user_cart = [];
            $num = [];
            $user_cart[session('user_goods.user_id')][$goods_id] = $goods_id;
            $num[session('user_goods.user_id')][$goods_id] = 1;
            $res = 1;
        } else {
            if (in_array($goods_id, $user_cart[session('user_goods.user_id')])) {
                $num[session('user_goods.user_id')][$goods_id]++;
                $res = 0;
            } else {
                $user_cart[session('user_goods.user_id')][$goods_id] = $goods_id;
                $num[session('user_goods.user_id')][$goods_id] = 1;
                $res = 1;
            }
        }

        session('user_cart', $user_cart);
        session('user_cart_num', $num);
        return $this->jsonSuccess('加入成功', $res);
    }

    /**
     * @return mixed
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function user_cart() {
        $this->assign('list', $this->getCartGoodsList());
        return $this->fetch();
    }

    /**
     * 查询商品列表
     * @param array $where
     * @return array|false|\PDOStatement|string|\think\Collection
     * @throws \think\exception\DbException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    private function getCartGoodsList($where=[], $nums=[]) {
        $user_cart = session('user_cart');
        if (empty($nums)) {
            $num = session('user_cart_num');
        } else {
            $num = $nums;
        }
        if (empty($user_cart[session('user_goods.user_id')])) {
            return [];
        }

        if (empty($where)) {
            $where = ['id' => ['in', $user_cart[session('user_goods.user_id')]]];
        }
        $where['is_sale'] = 1;
        $model = new Goods();
        $list = $model->where($where)->field('id,title,img,unit_price')->select();
        foreach ($list as &$v) {
            $v['num'] = empty($num[session('user_goods.user_id')][$v['id']]) ? 1 : $num[session('user_goods.user_id')][$v['id']];
        }
        return $list;
    }

    public function delCartGoods() {
        $id = input('post.id', 0, 'intval');
        if ($id <= 0) {
            return $this->jsonError('缺少必要参数');
        }
        $user_cart = session('user_cart');
        $num = session('user_cart_num');
        if (empty($user_cart[session('user_goods.user_id')])) {
            return $this->jsonSuccess('操作成功');
        }
        unset($user_cart[session('user_goods.user_id')][$id]);
        unset($num[session('user_goods.user_id')][$id]);
        session('user_cart', $user_cart);
        session('user_cart_num', $num);
        return $this->jsonSuccess('操作成功');
    }

    /**
     * 下单
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\ModelNotFoundException
     */
    public function user_place() {
        $goods_ids = $_POST['goods_id'];
        $nums = $_POST['num'];
        if (!is_array($goods_ids)) {
            $num = [];
            $nums = explode(',', $nums);
            $goods_ids = explode(',', $goods_ids);
            foreach ( $nums as $k=>$v) {
                $num[session('user_goods.user_id')][$goods_ids[$k]] = $v;
            }
            $nums = $num;
        }

        if (!empty($goods_ids)) {
            //购物车下单
            $goods_list = $this->getCartGoodsList(['id'=>['in', $goods_ids]], $nums);
            if (empty($goods_list)) {
                return $this->myReturn('请选中要购买的商品', url('index'));
            }
            $ids = [];
            $order_amount = 0;
            foreach ($goods_list as $k=>$v) {
                $ids[] = $v['id'];
                $order_amount += $v['unit_price'] * $v['num'];
                unset($goods_list[$k]['id'], $goods_list[$k]['checked'], $goods_list[$k]['spec_arr']);
            }
            $order_amount = amountFormat($order_amount);
        }

        if (!isAjaxPost()) {
            //显示页面
            $this->assign('goods_list', $goods_list);
            $this->assign('order_amount', $order_amount);
            return $this->fetch();
        }

        /************************ajax下单************************/
        set_time_limit(0);
        $user = session('user');
        $shop_id = $user['id'];

        $order = [
            'orderno' => createOrder(),
            'user_id' => session('user_goods.user_id'),
            'status' => 5,
            'amount' => $order_amount,
            'type' => 2,
            'add_time' => time(),
            'shop_id' => $shop_id
        ];

        $order_model = new \app\common\model\Order();
        $order_model->startTrans();
        //插入订单
        if (!$order_model->insert($order)) {
            $order_model->rollback();
            return $this->jsonError('订单提交失败');
        }

        //保存商品
        $oid = $order_model->getLastInsID();
        foreach ($goods_list as $k=>&$v) {
            $v = $v->toArray();
            $v['price'] = $v['unit_price'];
            $v['order_id'] = $oid;
            unset($goods_list[$k]['unit_price']);
        }
        if (!db::name('order_goods')->insertAll($goods_list)) {
            $order_model->rollback();
            return $this->jsonError('订单提交失败');
        }

        $pid = db::name('user')->where(['id'=>$order['user_id']])->value('pid');
        if (!calFxEarnings($order['amount'], $pid)) {
            $order_model->rollback();
            return $this->jsonError('操作失败');
        }
        if (!addPrevFxAmount($order['amount'], $pid)) {
            $order_model->rollback();
            return $this->jsonError('操作失败');
        }

        $cart = session('user_cart');
        $num = session('user_cart_num');
        foreach ($cart[$order['user_id']] as $k=>$v) {
            if (in_array($v, $goods_ids)) {
                unset($cart[$order['user_id']][$k]);
                unset($num[$order['user_id']][$k]);
            }
        }
        session('user_cart', $cart);
        session('user_cart_num', $num);

        $order_model->commit();
        return $this->jsonSuccess('订单提交成功');
    }

    public function user_order() {
        $user = session('user');
        $this->assign('shop_id', $user['id']);
        return $this->fetch();
    }


    /**
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function getUserList() {
        !isAjaxPost() && die;
        $user_id = session('user.id');
        $keywords = input('post.keywords', '', 'trim');
        $where = [
//            'pid' => $user_id,
//            'is_add' => 1
        ];
        !empty($keywords) && $where['name|tel'] = ['like', "%$keywords%"];

        $model = new \app\common\model\User();
        $pageSize = 10;
        $list = $model->where($where)->order('id desc')->field('id,name,tel,code')->paginate($pageSize, true);

        return $this->jsonSuccess('', $list);
    }
    /********* 商家中心结束 **********/
    /**
     * 实名认证
     *
     * @return void
     * @author 阿文
     * @date 2021-11-17
     */
    public function auth()
    {
        if (isAjaxPost()) {
            $info=input('post.');
            $info['uid']=$this->user['id'];
            $info['ucode']=$this->user['code'];
            $info['create_time']=time();
            $one=db('renzheng')->where(['uid'=>$this->user['id']])->find();
            if(!$one){
                $res=db('renzheng')->insert($info);
            }else{
                $info['state']=0;
                $res=db('renzheng')->where(['id'=>$one['id']])->update($info);
            }
            if($res){
                return $this->jsonSuccess('提交成功');
            }else{
                return $this->jsonError('提交失败');
            }
            
        }else{
            $one=db('renzheng')->where(['uid'=>$this->user['id']])->order('id desc')->find();
            $this->assign('one',$one);
            return $this->fetch();
        }
        return $this->fetch();
    }

    public function method()
    {
        return $this->fetch();
    }
    public function method_info()
    {
        if (request()->isAjax()) {
            $param = $this->request->post();

            $scan = $param['type'] == 'bank' ? 'bank' :($param['type']=='usdt'?'usdt':'img') ;
            $validate = validate('Common');
            if (!$validate->scene($scan)->check($param)) {
                return $this->jsonError($validate->getError());
            }
            $msg = '修改支付方式：';
            if ($scan == 'bank') {
                if ($param['bank_name'] != $this->user['bank_name']) {
                    $title = $this->user['bank_name'] ? $this->user['bank_name'] : '暂无';
                    $msg .= '修改银行名称【' . $title . '】修改为【' . $param['bank_name'] . '】，';
                }
                if ($param['bank_account'] != $this->user['bank_account']) {
                    $title = $this->user['bank_account'] ? $this->user['bank_account'] : '暂无';
                    $msg .= '修改银行户名【' . $title . '】修改为【' . $param['bank_account'] . '】，';
                }
                if ($param['bank_number'] != $this->user['bank_number']) {
                    $title = $this->user['bank_number'] ? $this->user['bank_number'] : '无';
                    $msg .= '修改银行卡号【' . $title . '】修改为【' . $param['bank_number'] . '】，';
                }
                U::update($param, ['id' => $this->user['id']], true);
            }else if($param['type']=='usdt'){
                if ($param['usdt_addr'] != $this->user['usdt_addr']) {
                    $title = $this->user['usdt_addr'] ? $this->user['usdt_addr'] : '暂无';
                    $msg .= '修改USDT地址【' . $title . '】修改为【' . $param['usdt_addr'] . '】，';
                }
                U::update($param, ['id' => $this->user['id']], true);

            } else {


                $title = $param['type'] == 'alipay' ? '支付宝' : '微信';
                $y = $this->user[$param['type'] . '_img'];
                $n = $param['img'];
                if ($param['type'] . '_img' != $y) {
                    if (!$this->user[$param['type'] . '_img']) {
                        $msg .= '首次绑定' . $title . '收款码：<a target="_blank" href="' . $n . '">
                        <img src="' . $n . '" style="width: 50px"/></a>';
                    } else {
                        $msg .= '修改' . $title . '收款码：<a target="_blank" href="' . $y . '">
                        <img style="width: 50px" src="' . $y . '"/></a>修改为<a target="_blank" href="' . $n . '">
                        <img style="width: 50px" src="' . $n . '"/></a>';
                    }
                }
                $yn = $this->user[$param['type'] . '_name'] ? $this->user[$param['type'] . '_name'] : '暂无';
                $nn = $param['name'];
                if ($yn != $nn) {
                    $msg .= '修改' . $title . '真实姓名：【' . $yn . '】修改为【' . $nn . '】';
                }
                U::update([
                    $param['type'] . '_img' => $param['img'],
                    $param['type'] . '_name' => $param['name'],
                    $param['type'] . '_account' => $param['account'],

                ], ['id' => $this->user['id']]);

            }
            Logs::adds($msg, $this->user['id'], $this->user['code']);
            $route = 'task/method_info.log';
            Logs::write($route, $this->user['code'] . $msg);
            return $this->jsonSuccess('已保存');
        }
        $type = input('type');
        $way = ['wechat' => '微信', 'alipay' => '支付宝', 'bank' => '银行卡','usdt' => 'USDT'];
        if (!$way[$type]) $this->redirect('/');
        $this->assign('way', $way);
        $this->assign('type', $type);
        return $this->fetch();
    }
    //签到
    public function sign()
    {
        $morn = explode(',',config('morning'));
        $noon = explode(',',config('noon'));
        $night = explode(',',config('night'));
        $his = date('H:i:s');
        $is=1;
        if(($his < $morn[0] || $his > $morn[1]) && ($his < $noon[0] || $his > $noon[1]) && ($his < $night[0] || $his > $night[1])){
            $is=0;
        }
        if($his > $morn[0] && $his < $morn[1]){
            $qu=config('morning');
        }else if($his > $noon[0] && $his < $noon[1]){
            $qu=config('noon');
        }else{
            $qu=config('night');

        }
        $date = date('Y-m-d');
        $is_q = db('member_sign')->where(['uid' => $this->user['id'], 'date' => $date,'time_q'=>$qu])->find();
        if (request()->isAjax()) {
            $param = $this->request->post();
            if(!$is){
                return $this->jsonError('不在签到时间内');

            }
            if($is_q){
                return $this->jsonError('已签到');

            }
            if(!$param['video']){
                return $this->jsonError('视频必传');
            }
           
            $res=db('member_sign')->insert([
                'uid' => $this->user['id'],
                'ucode' => $this->user['code'],
                'uname' => $this->user['name'],
                'date' => $date,
                'date_time' => strtotime($date),
                'create_time' => time(),
                'integral' => 0,
                'video' =>$param['video'] ,
                'time_q' =>$qu ,
            ]);
            if(!$res){
                return $this->jsonError('签到失败');
            }
            return $this->jsonSuccess('签到成功');
        }
        $this->assign('is',$is);
        $this->assign('is_q',$is_q);
        return $this->fetch(); 
    }
    /**
     *  账户明细
     */
    public function purse()
    {
        $type = input('t');
        if (request()->isAjax()) {
            $page = input('page', 1);
            $list = (new Account())->get_account($type, $page, $this->user['id']);
            return json(['code' => 1, 'result' => $list, 'page' => $page]);
        }
        $title = [
            'bonus2' => '欢乐豆',
            'bonus1' => '欢笑豆',
            'bonus' => '奖金',
            'yeji' => '销售业绩',

            
        ];
        $_user=$this->user;
        if (!$title[$type]) $this->redirect('/user');
        $this->assign('title', $title[$type]);
        $this->assign('type', $type);
        $this->assign('_user', $_user);

        // if($type=='cash') $this->user[$type] = Account::where(['member_id'=>$this->user['id'],'intro'=>['in',['拼中','未拼中','幸运奖','拼团红包','每日释放','代理奖']]])->sum('amount');
        $this->assign('amount', $this->user[$type]);

        return $this->fetch();
    }

    public function statistics()
    {
        //伞下单数
        // $team_id=(new Rec())->where(['member_id'=>$this->user['id'],'is_group'=>1])->column('new_member_id');
        // $zhitui_id=db('user')->where(['referee_id'=>$this->user['id'],'is_active'=>1])->column('id');
        // $data['team']=db('user')->where(['id'=>['in',$team_id]])->sum('head');
        // $data['rec']=db('user')->where(['id'=>['in',$zhitui_id]])->sum('head');
        // $this->assign('data',$data);
        return $this->fetch();
    }

    public function state($id, $key, $val)
    {
        return $this->editState('user', $id, $key, $val);
    }
}